#!/usr/bin/env python
# @FileName :user.py
# @Time :2025/8/20 10:14
# @Author :chenjiajun
from datetime import datetime

from . import db
from werkzeug.security import generate_password_hash, check_password_hash


class User(db.Model):
    __tablename__ = 'user'
    user_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    user_account = db.Column(db.String(256), nullable=False,unique=True)
    user_password = db.Column('password',db.String(512), nullable=False)
    role = db.Column(db.String(256), nullable=False)
    add_time = db.Column(db.DateTime, default=datetime.now)

    @property
    def password(self):
        return self.user_password

    # 当执行user.password = <value>时，就会执行下面函数里面的操作
    @password.setter
    def password(self, value):
        self.user_password = generate_password_hash(value)

    @classmethod
    def create_user(cls, user_account, user_password, role=0):
        user = cls()
        user.user_account = user_account
        user.password = user_password
        user.role = role
        db.session.add(user)
        db.session.commit()

    @staticmethod
    def delete_user(id):
        user = User.query.get(id)
        db.session.delete(user)
        db.session.commit()

    @staticmethod
    def modify_user(id, user_account, role, user_password=None):
        user = User.query.get(id)
        user.user_account = user_account
        user.role = role
        if user_password:
            user.password = user_password
        db.session.add(user)
        db.session.commit()

    def keys(self):
        return 'user_id', 'user_account', 'role', 'add_time'


    def __getitem__(self, key):
        if key == 'add_time':
            self.add_time = self.add_time.strftime("%Y-%m-%d %H:%M:%S")
            return self.add_time
        else:
            return getattr(self, key)

